package com.fare.taluo.action.send.report;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.annotation.Resource;
import javax.inject.Inject;

import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.fare.taluo.BaseFdcAction;
import com.fare.taluo.action.csairReport.CsairReportAction;
import com.fare.taluo.action.price.rubik.PriceRubikAction;
import com.fare.taluo.application.queue.QueueEmailMessageApplication;
import com.fare.taluo.application.system.email.ReportEmailApplication;
import com.fare.taluo.core.domain.system.EmailEntity;
import com.fare.taluo.queue.CreatePersistenceTask;
import com.fare.taluo.queue.ExportCsairReportInlandQuartzJob;
import com.fare.taluo.queue.ExportCsairTaobaoQuartzJob;
import com.fare.taluo.queue.ExportOtaTemplateQuartzJob;
import com.fare.taluo.queue.ExportZHairReportQuartzJob;
import com.fare.taluo.queue.ReportOTADomestic;
import com.fare.taluo.util.DateUtils;
import com.fare.taluo.vo.queue.QueueEmailMessageVO;
import com.fare.taluo.vo.queue.QueueEmailMessageVOListByDate;
import com.fare.taluo.vo.reportemail.EmailVO;



/**
 * 手动触发报表
 * @author gan 
*/
@Controller("manualReportAction")
@Scope("prototype")
@Namespace("/")
public class ManualReportAction extends BaseFdcAction{
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 3507752207012805129L;

	@Inject
	private CsairReportAction csairReportAction;
	
	@Inject
	private PriceRubikAction priceRubikAction;
	
	@Inject
	private ExportOtaTemplateQuartzJob exportOtaTemplateQuartzJob;
	
	@Inject
	private ExportCsairTaobaoQuartzJob exportCsairTaobaoQuartzJob;
	
	@Inject 
	private ReportOTADomestic reportOTADomestic;
	
	@Resource(name="queueEmailMessageApplication")
	private QueueEmailMessageApplication queueEmailMessageApplication;
	
	private ExportZHairReportQuartzJob exportZHairReportQuartzJob;
	
	@Inject
	private CreatePersistenceTask createPersistenceTask;
	
	private ExportCsairReportInlandQuartzJob exportCsairReportInlandQuartzJob;
	
	@Resource(name ="reportEmailApplication")
//	@Inject
	private ReportEmailApplication reportEmailApplication;
	
	private List<EmailVO> emailList;
	
	
	private List<QueueEmailMessageVOListByDate> listDataByDate;
	
	private List<QueueEmailMessageVO> listVo;
	
	private String method;
	
	private String usernameList;
	//进入操作触发页面
	public String toIntoJSP() {
		
		///手动持久化
		/*try {
			createPersistenceTask.execute();
		} catch (Exception e1) {
			e1.printStackTrace();
		}*/
				
		
		int pageSize=10;//10一页条数据
		EmailEntity en =new EmailEntity();
		//Page<QueueEmailMessageEntity> pageEntity= en.findEntityByPage(null, 1, pageSize);
		//pageComponent = PageComponent.getInstance(pageEntity);
		
		listVo=queueEmailMessageApplication.findEntityByPage(null, 1, pageSize);
		listDataByDate=queueEmailMessageApplication.findListByList(listVo);
		emailList=reportEmailApplication.findAllEmail(-1);
		returnPageURL = "/fare/manualTriggerReport/manualTReport.jsp";
		return "dispatcher";
	}
	
	
	//页面action
	public String sendReport() throws Exception {
		String emailStr=usernameList.replaceAll(" ", "");
		String result="";
		try{
			if(method.equals("csairInternationalReport")){//南航国际报表
				csairReportAction.setEmail(emailStr);
				csairReportAction.execute();
			}if(method.equals("internationalOTA")){//国际旅行航线OTA
				exportOtaTemplateQuartzJob.setEmail(emailStr);
				exportOtaTemplateQuartzJob.execute();
			}if(method.equals("taobaoFlagship")){//淘宝旗舰店与代理人差价报表
				priceRubikAction.setEmail(emailStr);
				priceRubikAction.execute();
			}if(method.equals("CADomesticReport")){//国航国内OTA
				reportOTADomestic.setEmail(emailStr);
				reportOTADomestic.execute();			
			}if(method.equals("CSDomesticReport")){//南航国内航线价差
				exportCsairReportInlandQuartzJob.setEmail(emailStr);
				exportCsairReportInlandQuartzJob.execute();
			}if(method.equals("ZHPriceReport")){//深航官网与渠道价差报表
				exportZHairReportQuartzJob.setEmail(emailStr);
				exportZHairReportQuartzJob.execute();
			}
			if(method.equals("CSTaobaoReport")){//南航淘宝价差
				exportCsairTaobaoQuartzJob.setEmail(emailStr);
				exportCsairTaobaoQuartzJob.execute();
			}
			result="SUCCESS";
		}catch (Exception e) {
			result=e.getMessage();
		}
		if(result==null || result==""){
			result="系统找不到指定的路径。";
		}
		super.toJSONHtmlOut(result);
//		response.setContentType("text/html;charset=UTF-8"); 
//		response.getWriter().print(result);
		return null;
	}
	
	
	
	//手动下载报表Action(单表下载)
	public void download(){
		//传报表的地址
		String filePath=request.getParameter("filePaths");
		String subjectName=request.getParameter("subjectNames");
		try {
			filePath = new String(filePath.getBytes("iso-8859-1"),"UTF-8");
			filePath=java.net.URLDecoder.decode(filePath,"UTF-8");
			subjectName = new String(subjectName.getBytes("iso-8859-1"),"utf-8");
			subjectName=java.net.URLDecoder.decode(subjectName,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		downOneFile(filePath,subjectName);
		
	//	return "dispatcher";
	}
	
	//手动下载报表Action(某一天的所有的报表)
	public void downloadAllByDate(){
		String reportCreateDate =request.getParameter("reportCreateDate");
		
		try {
			reportCreateDate=new String(reportCreateDate.getBytes("iso-8859-1"),"UTF-8");
			reportCreateDate=java.net.URLDecoder.decode(reportCreateDate,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		Date createDates=DateUtils.strToDate(reportCreateDate, "yyyy-MM-dd");
		List<QueueEmailMessageVO> listVO=queueEmailMessageApplication.findEntityByDate(createDates);
		if(listVO.size()>0){
			downloadAllFileByDate(listVO,reportCreateDate);
		}
		
		//return "dispatcher";
	}
	
	
	
	public void downOneFile(String filePath,String subjectName) {
		InputStream is = null;
		OutputStream out=null;
		try {
			File file = new File(filePath);  
			is = new FileInputStream(file); 
			String fileName = null;

			fileName = subjectName+".xls";
			out = response.getOutputStream();
			// response.reset();
			// 设置输出的格式
			// response.setContentType("application/pdf;charset=UTF-8");
			// HttpServletResponse response =
			response.setContentType("application/octet-stream;charset=UTF-8");
			if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0){
				fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
			}else{
				fileName = URLEncoder.encode(fileName, "UTF-8");//其他浏览器
			}
			response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
			// 循环取出流中的数据
			byte[] b = new byte[1024*1024];
			int len;
			while ((len = is.read(b)) > 0){
				out.write(b, 0, len);
			}
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			
			try {

				if (is != null) {
					is.close();
				}out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}

	}
	
	
	
	//打包下载 by date
	public void downloadAllFileByDate(List<QueueEmailMessageVO> listVO, String dateStr) {
		InputStream is = null;
		OutputStream out = null;
		ZipOutputStream zipOut = null;
		String zipFileName = dateStr + ".zip";
		try {
			out = response.getOutputStream();
			if (request.getHeader("User-Agent").toLowerCase()
					.indexOf("firefox") > 0) {
				zipFileName = new String(zipFileName.getBytes("UTF-8"),
						"ISO8859-1");// firefox浏览器
			} else {
				zipFileName = URLEncoder.encode(zipFileName, "UTF-8");// 其他浏览器
			}
			response.setHeader("Content-Disposition", "attachment; filename="
					+ zipFileName);// 输出 文件头
			response.setContentType("application/zip;charset=UTF-8");
			zipOut = new ZipOutputStream(out);
			// zipOut = new ZipOutputStream(new FileOutputStream(zipFileName));
			for (int i = 0; i < listVO.size(); i++) {
				QueueEmailMessageVO vo = listVO.get(i);
				String filePath = vo.getAttachPath();
				String fileName = vo.getSubject();
				fileName = fileName + ".xls";
				File file = new File(filePath);
				ZipEntry ze = new ZipEntry(fileName);
				is = new FileInputStream(file);

				zipOut.putNextEntry(ze);
				// 循环取出流中的数据
				byte[] b = new byte[1024 * 1024];
				int len;
				while ((len = is.read(b)) > 0) {
					zipOut.write(b, 0, len);
				}

				out.flush();
				zipOut.closeEntry();
				is.close();
			}
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public List<EmailVO> getEmailList() {
		return emailList;
	}


	public void setEmailList(List<EmailVO> emailList) {
		this.emailList = emailList;
	}

	public String getMethod() {
		return method;
	}

	public void setMethod(String method) {
		this.method = method;
	}

	public String getUsernameList() {
		return usernameList;
	}

	public void setUsernameList(String usernameList) {
		this.usernameList = usernameList;
	}


	public List<QueueEmailMessageVOListByDate> getListDataByDate() {
		return listDataByDate;
	}


	public void setListDataByDate(List<QueueEmailMessageVOListByDate> listDataByDate) {
		this.listDataByDate = listDataByDate;
	}


	public List<QueueEmailMessageVO> getListVo() {
		return listVo;
	}


	public void setListVo(List<QueueEmailMessageVO> listVo) {
		this.listVo = listVo;
	}

	
	
}
